<template>
  <div class="flex flex-col h-full">
    <a-card>
      <div class="flex justify-between items-center">
        <a-button type="primary" class="mr-4" @click="router.go(-1)"> 返回 </a-button>
        <a-descriptions class="mt-3" :column="4">
          <a-descriptions-item label="单号"> {{ formState.bsdh || '-' }}</a-descriptions-item>
          <a-descriptions-item label="出库仓库"> {{ formState.ckmc || '-' }}</a-descriptions-item>
          <a-descriptions-item label="制单人">{{ formState.qrr || empName || '-' }}</a-descriptions-item>
          <a-descriptions-item label="制单时间">{{ formState.addtime || '-' }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-card>
    <a-card class="mt-2 flex-1">
      <BaseTable
        :data-source="dataSource"
        column-code="000152"
        :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')"
        :loading="loading"
        max-fill
        :extra-height="64"
      >
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'xh'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'lb'">
            <a-radio-group v-model:value="record.bslx" @change="onRadioEdit($event, record)">
              <a-radio :value="0">报损</a-radio>
              <a-radio :value="1">报溢</a-radio>
            </a-radio-group>
          </template>
          <template v-if="column.dataIndex === 'mc'">
            <EditCell>
              <SelectMedicine
                :value="{ mc: record.mc, gg: record.gg, cj: record.cj }"
                type="检验移动"
                :search-params="{ ckbh: formState?.ckbh, lx: 0 }"
                @select="onSelectMedicine($event, record)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'ph'">
            <EditCell>
              <a-select v-model:value="record.ph" :options="batchList" placeholder="请选择" @change="onSelectBatch($event, record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'sl'">
            <EditCell>
              <BaseInput
                v-model:value="record.sl"
                v-input:int
                :auto-focus="focusCell === record.key"
                class="text-right"
                placeholder="请输入"
                @blur="editRow(record)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'yy'">
            <EditCell>
              <a-input v-model:value="record.bsyy" placeholder="请输入" @blur="editRow(record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <ConfirmModal @confirm="onDelete(record)">
              <a-button type="text" danger size="small">删除</a-button>
            </ConfirmModal>
          </template>
        </template>
        <template #footer>
          <div class="text-center sticky bottom-0">
            <a-button class="mr-2" @click="addRow()"> 新增一条 </a-button>
            <a-button type="primary" @click="saveNewRows()"> 保存 </a-button>
          </div>
        </template>
      </BaseTable>
    </a-card>
  </div>
</template>

<script setup>
import { ref, watchEffect } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'
import BaseTable from '@/components/BaseTable'
import ConfirmModal from '@/components/ConfirmModal'
import { post } from '@/utils/request'
import useUserStore from '@/store/user'
import EditCell from '@/components/EditCell'

const formState = ref({})
const focusCell = ref({})
const loading = ref(false)
const dataSource = ref([])
const batchList = ref([])
const route = useRoute()
const router = useRouter()
const { empName } = useUserStore()
const editRow = (row) => !row.isNew && fetchSave(row)
const fetchSave = async (row) => {
  row.bsdh = formState.value.bsdh
  if (row.sl > Math.abs(parseInt(row.dqkc)) && row.bslx === 0) {
    dataSource.value = dataSource.value.map((item) => {
      if (row?.lsh) {
        if (item.lsh === row.lsh) {
          item.sl = 0
        }
      } else {
        if (item.key === row.key) {
          item.sl = 0
        }
      }
      return item
    })
    return message.error('数量不可大于库存量')
  }
  row.sl = row.bslx === 1 ? -Math.abs(row.sl) : Math.abs(row.sl)
  delete row.mc
  const { code, msg } = await post('/materials/psiform/doSaveLossOverflowDetail', row)
  if (code !== 0) return message.error(msg || '操作失败')
  getDetailData()
  message.destroy()
  message.success(row.isNew ? '新增成功' : '修改成功')
}
const saveNewRows = async () => {
  const newRow = dataSource.value.filter((item) => item.isNew)
  newRow.forEach((item) => {
    if (item.ypbh && item.sl) {
      fetchSave(item)
    } else {
      message.destroy()
      message.error('请填写完整信息')
    }
  })
}

const onSelectMedicine = (medicine, row) => {
  row.mc = medicine?.mc
  row.cj = medicine?.cj
  row.yxq = medicine?.yxq
  row.ypbh = medicine?.bh
  row.ph = medicine?.ph
  row.gg = medicine?.gg
  row.dqkc = medicine?.sl
  row.dw = medicine?.dw
  row.ypbh = medicine?.ypbh
  focusCell.value = row.key

  if (!row?.bslx) {
    row.bslx = 0
  }
  editRow(row)
  getDrugBatchNumber(medicine)
}
const getDrugBatchNumber = async (medicine) => {
  const { data, code, msg } = await post('/materials/comprehenive/getDrugBatchNumber', {
    ckckbh: formState.value.ckbh,
    ypbh: medicine.bh
  })
  if (code !== 0) return message.error(msg)
  batchList.value = data.map((item) => {
    return {
      label: item.ph,
      value: item.ph,
      dqkc: item.dqkc
    }
  })
}

const onRadioEdit = (value, row) => {
  dataSource.value = dataSource.value.map((item) => {
    if (row?.lsh) {
      if (item.lsh === row.lsh) {
        item = { isNew: true, addtime: dayjs().format('YYYY-MM-DD HH:mm:ss'), bslx: value.target.value, lsh: row.lsh }
      }
    } else {
      if (item.key === row.key) {
        item = { key: row.key, isNew: true, addtime: dayjs().format('YYYY-MM-DD HH:mm:ss'), bslx: value.target.value }
      }
    }
    return item
  })
}

const onSelectBatch = (value, row) => {
  const item = batchList.value.find((val) => val.value === value)
  row.dqkc = item.dqkc
}

//添加行
const addRow = () => {
  const key = `row-${dataSource.value.length}`
  const addRow = { key, isNew: true, addtime: dayjs().format('YYYY-MM-DD HH:mm:ss'), bslx: 0 }
  dataSource.value.push(addRow)
}
const getMainData = async () => {
  const { data, code } = await post('/materials/psiform/getLossOverflowHeadList', {
    mcbm: route.query?.bsdh
  })
  if (code === 0) {
    formState.value = data[0]
  }
}
const getDetailData = async () => {
  loading.value = true
  const { data, code } = await post('/materials/psiform/getLossOverflowDetailList', {
    bsdh: route.query?.bsdh,
    pageNum: 1,
    pageSize: 999
  })
  loading.value = false
  if (code === 0) {
    dataSource.value = data
  }
}
const onDelete = async (row) => {
  if (row.lsh) {
    const { code, msg } = await post('/materials/psiform/doDeleteLossOverflowDetail', {
      dh: row?.bsdh,
      lsh: row?.lsh
    })
    if (code !== 0) return message.error(msg || '删除失败')
    message.success(msg)
    getDetailData()
  } else {
    dataSource.value = dataSource.value.filter((item) => {
      return item.key !== row.key
    })
    message.success('删除成功')
  }
}
watchEffect(() => {
  if (route.query?.bsdh) {
    getMainData()
    getDetailData()
  }
})
</script>
<style lang="less" scoped>
:deep(.ant-card-head) {
  padding-left: 8px;
}
</style>
